<template>
  <div style="height: 100%;">
    <div class="search">
      <div class="search-input">
        <div class="u-search">
          <u-search
            v-model.trim="form.keyWord"
            shape="square"
            :show-action="false"
            :animation="true"
            @change="changeWord"
          ></u-search>
        </div>
        <div class="btn" @click="search()">搜索</div>
      </div>
      <!-- 未搜索时候的历史记录 -->
      <div class="history" v-if="form.keyWord == '' && skuList.length">
        <div class="h3">历史搜索</div>
        <div class="lis">
          <div
            class="li"
            v-for="(tab, index) in skuList"
            :key="index"
            @click="changeSku(tab)"
          >
            {{ tab }}
          </div>
        </div>
      </div>
      <!-- 搜索时候的匹配结果 -->
      <div class="cell" v-if="form.keyWord && !showRes">
        <u-cell-group>
          <u-cell
            v-for="item in likeKeys"
            :key="item"
            :title="item"
            :arrow="false"
            @click="getResult(item)"
          ></u-cell>
        </u-cell-group>
      </div>
      <!-- 搜索结果 -->
      <div class="result" v-if="form.keyWord && showRes">
        <div class="tabs">
          <div class="tab"  v-for="(tab,index) in tabs" :key="index" :class="active === index ? 'act-tab' : ''" @click="changeTab(index)">
            <span>
              <u>{{ tab.title }}</u>
              <img v-if="paixuVal===0 && index === 1" mode="aspectFill" :src="icon.paixu" alt="">
              <img v-if="paixuVal===1 && index === 1" mode="aspectFill" :src="icon.zhengxu" alt="">
              <img v-if="paixuVal===2 && index === 1" mode="aspectFill" :src="icon.daoxu" alt="">
            </span>
            <img v-if="active === index" mode="aspectFill" :src="icon.act" class="active"/>
          </div>
        </div>
        <scroll-view class="list"
            :scroll-y="true"
						:refresher-enabled="true"
						:enable-back-to-top="true"
						:scroll-anchoring="true"
						:refresher-triggered="triggered"
						@refresherrefresh="onRefresh"
						@scrolltolower="onLower">

            <div class="shop-li" v-for="(item,index) in goodsList" :key="index" @click="goDetail(item.spuCode)">
              <image :src="item.coverImage" class="img"/>
              <div class="shop-content">
                <div class="title">{{item.productName}}</div>
                <div class="num" v-if="item.originalPrice">￥{{item.originalPrice}}</div>
								<div class="kc">库存：{{ item.stockNum || 0 }} {{ item.unit || '件' }}</div>
                <div class="bottom">
                  <div class="left" v-if="auth_token">
                    <div class="vip">
                      <img v-if="levelName" :src="icon.vip" alt="">
											<span>{{levelName || '普通用户'}}</span>
                    </div>
                    <div class="money">￥{{item.salesPrice}}</div>
                  </div>
                  <div class="left" v-else>
										<div class="vip logins">登录查看价格</div>
									</div>
									<image v-if="auth_token" class="icon" :src="item.stockNum ? icon.exchange : icon.no_exchange" @click.stop="showSku(item.spuCode)"/>
                </div>
              </div>
            </div>
            <div class="diver" v-if="finished && goodsList.length">
							<u-divider text="没有更多了"></u-divider>
						</div>
            <div class="empty" v-if="showRes && goodsList.length == 0">
              <u-empty
                mode="search"
              ></u-empty>
            </div>
          </scroll-view>

      </div>
    </div>
    <!-- 弹出框Sku -->
    <u-popup :show="showSkuModal" mode="bottom" :round="16" @close="close" >
      <sku-modal v-if="showSkuModal" :productSpecsList="goodsInfo.productSpecsList" @goOrder="goOrder"></sku-modal>
    </u-popup>
  </div>
</template>

<script>
import auth from '../../api/auth'
import SkuModal from '../../components/SkuModal.vue'
export default {
  props: {
    placeholder: {
      type: String,
      default: '',
    },
  },
  components:{
    SkuModal
  },
  data() {
    return {
      active: null,
      icon:{
        exchange: require('../../static/exchange-icon.png'),
				no_exchange: require('../../static/no-exchange-icon.png'),
				vip:require('../../static/vip-icon.png'),
				act:require('../../static/active-icon.png'),
				paixu:require('../../static/paixu-icon.png'),
				zhengxu:require('../../static/zhengxu-icon.png'),
				daoxu:require('../../static/daoxu-icon.png'),
      },
      tabs:[
        {title:'销量',id:1},
        {title:'价格',id:2},
        {title:'上新',id:3},
      ],
      form:{
        keyWord: '',
        price: null,
        soldUnit: null,
        sort: null,
      },
      goodsInfo: {
        pic: [],
      },
      pageNum: 1,
			goodsCount:0,
      paixuVal: 0,
      finished: false,
			triggered: false,
      showRes: false,
      showSkuModal: false,
      skuAct: 0,
      skuList: [],
      goodsList:[],
      likeKeys: [],
      auth:null,
			auth_token:null,
			levelName: ''
    }
  },
  onShow() {
    this.auth = uni.getStorageSync('_AUTH_')
		this.auth_token = uni.getStorageSync('AUTH_TOKEN')
    if(this.auth_token) {
      this.memberGetUserInfo()
		}
    this.skuList = uni.getStorageSync('_SKULIST_')
  },
  methods: {
    async changeWord() {
      // this.showRes = false
      let res = await auth.searchLike({keyWord: this.form.keyWord.trim()})
      this.likeKeys = [...res]
      if(this.keyWord === '') {
        this.goodsList = []
        this.goodsCount = 0
        this.pageNum = 1
        this.finished = false
      }
    },
    search() {
      this.goodsList = []
      this.showRes = true
      let list = [...this.skuList]
      if(+this.form.keyWord) {list.push(this.form.keyWord.trim())}
      list = [...new Set(list)] 
      this.skuList = list.splice(0,10)
      uni.setStorageSync('_SKULIST_',this.skuList)
      if(this.active === 0) {
        this.form.soldUnit = 1
        delete this.form.price
        delete this.form.sort
      }else if(this.active === 1) {
        delete this.form.soldUnit
        delete this.form.sort
        if(this.paixuVal === 1) {
          this.form.price = 1
        } else if(this.paixuVal === 2) {
          this.form.price = 0
        } else {
          delete this.form.price
        }
      } else {
        this.form.sort = 1
        delete this.form.soldUnit
        delete this.form.price
      }
			this.getGoodsList()
    },
     // 获取我的页面信息
    async memberGetUserInfo() {
      let res = await auth.memberGetUserInfo();
      this.levelName = res.levelName 
    },
    changeSku(tab) {
      this.showRes = true
      this.form.keyWord = tab
			this.goodsList = []
      this.goodsCount = 0
      this.pageNum = 1
      this.finished = false
			this.search()
    },
    changeTab(index) {
      if(this.active === index && index === 1) {
        if(this.paixuVal === 1) {
          this.paixuVal = 2
        } else if(this.paixuVal === 2) {
          this.paixuVal = 1
        }
      } else {
        this.active = index
        if(index === 1) {
          this.paixuVal = 1
        } else {
          this.paixuVal = 0
        }
      }
      this.goodsList = []
      this.goodsCount = 0
      this.pageNum = 1
      this.finished = false
			this.search()
    },
    async getGoodsList() {
			let params = {
				pageNum:this.pageNum,
				pageSize: 10,
        ...this.form
			}
			let goodObj = await auth.productGetList(params)
			this.goodsList = [...this.goodsList,...goodObj.data]
			this.goodsCount = goodObj.pages
			if(this.pageNum == this.goodsCount) {
				this.finished = true
			}

		},
    goDetail(spuCode) {
			if(this.auth_token){
				uni.navigateTo({
					url: '/pages/FenLei/detail?spuCode=' + spuCode,
				})
			} else {
				uni.showToast({
					title:'登录查看商品详情~',
					icon:'none'
				})
			}
		},
    	  /**
     * 获取详情数据
     */
    async productGetOne(spuCode) {
      let res = await auth.productGetOne({spuCode})
      this.goodsInfo = res
			this.showSkuModal = true
    },
     // 获取分类菜单
		showSku(spuCode) {
			this.productGetOne(spuCode)
		},
    close() {
      this.showSkuModal = false
    },
    onRefresh() {
			this.triggered = true;
			this.finished=  false
			this.pageNum = 1
			this.goodsList = []
			this.getGoodsList()
      console.log("onRefresh");
      setTimeout(() => {
        this.triggered = false;
      }, 1000);
    },
		onLower() {
			if(this.pageNum < this.goodsCount) {
				this.pageNum++
				this.getGoodsList()
			} else {
				this.finished = true
			}
		},
    getResult(item) {
      this.showRes = true
      this.form.keyWord = item
			this.search()
    },
    async goOrder(obj) {
			this.showSkuModal =  false
			obj.skuObj.productId = this.goodsInfo.id
			console.log(obj)
			/**
			 * obj.type=1加入购物车
			 * 参数
			 * {
			 * "productAmount": 0,
					"productId": 0,
					"productSkuId": 0,
			 * }

			 obj.type=2商品详情页立即购买
			 进入提交商品订单页面source 订单创建来源，1：商品详情页，2：购物车列表

			 向下个页面传值
			 "productAmount": 0,
				"productId": 0,
				"productSkuId": 0,
				"source": 1,
			 * 
			 * */ 
			switch (obj.type) {
				case 1:
					await auth.addOderCart(obj.skuObj)
          uni.showToast({title:'添加成功，在购物车等亲！'})
				break;
				case 2:
					uni.navigateTo({
						url: `/pages/GouWuChe/jieSuan?totalMoney=${obj.totalMoney}&skuObj=${JSON.stringify(obj.skuObj)}&source=1`
					})
				break;
			}
    }
  },
}
</script>

<style lang="scss" scoped>
.search {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .search-input {
    padding: 32rpx;
    display: flex;
    .u-search {
      flex: 1;
    }
    .btn {
      width: 120rpx;
      line-height: 62rpx;
      text-align: center;
      color: #fff;
      background: #FC6420;
      margin-left: 16rpx;
      border-radius: 16rpx;
    }
  }
  .history {
    flex: 1;
    margin: 32rpx;
    margin-top: 0;
    overflow: hidden;
    .h3 {
      font-size: 28rpx;
      line-height: 56rpx;
      font-weight: 500;
    }
    .lis {
      display: block;
      .li {
        float: left;
        line-height: 36rpx;
        font-size: 24rpx;
        padding: 20rpx;
        color: #8c9398;
        background: #f5f7f9;
        border-radius: 8rpx;
        margin-right: 24rpx;
        margin-bottom: 24rpx;
      }
      .sec-act-tab {
        color: #FC6420;
        background: #FFF1F1;
      }
    }
  }
  .cell {
    flex: 1;
    margin: 0 32rpx;
  }
  .result {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .tabs {
      display: flex;
      height: 80rpx;
      background: #fff;
      .tab {
        flex: 1;
        display: flex;
        flex-direction: column;
        span {
          display: flex;
          justify-content: center;
          align-items: center;
          u {
            font-size: 24rpx;
            line-height: 44rpx;
            text-align: center;
          }
          img {
            width: 16rpx;
            height: 28rpx;
            margin-left: 4rpx;
          }
        }
        .active {
					width: 54rpx;
					height: 12rpx;
          margin: 0 auto;
				}
      }
      .act-tab {
        span {
          font-weight: 500;
        }
      }
    }
      .list {
        flex: 1;
        background: #F5F7F9;
        padding: 32rpx;
        overflow: auto;
        box-sizing: border-box;
        .shop-li {
          display: flex;
          padding: 20rpx;
          margin-bottom: 32rpx;
          background: #fff;
          .img {
            width: 160rpx;
            height: 160rpx;
            border-radius: 16rpx;
          }
          .shop-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 16rpx;
            overflow: hidden;
            .title {
              color: #444;
              font-size: 28rpx;
              font-weight: 500;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }
            .num {
              // text-decoration: line-through;
              color: #FC3D1C;
              font-size: 36rpx;
            }
            .kc {
              color: #666;
              font-size: 20rpx;
            }
            .bottom {
              display: flex;
              justify-content: space-between;
              .left {
                display: flex;
                .vip {
                  width: 92rpx;
                  height: 36rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-size: 20rpx;
                  background: linear-gradient( 153deg, #F6EFE5 0%, #FDEBDB 100%);
                  img {
                    width: 24rpx;
                    height: 24rpx;
                    margin-right: 6rpx;
                  }
                }
                .logins{
                  width: 180rpx;
                }
                .money {
                  width: 112rpx;
                  height: 36rpx;
                  line-height: 36rpx;
                  font-size: 20rpx;
                  color: #FC3D1C;
              	  background: #FFF6EF;
                  text-align: center;
                  border-radius: 0rpx 8rpx 8rpx 0rpx;
                }
              }
              .icon {
                width: 36rpx;
                height: 36rpx;
              }
            }
          }
        }
        .diver {
          margin-bottom: 60rpx;
          overflow: hidden;
        }
        .empty {
          width: 100%;
          height: 100%;
          overflow: hidden;
          display: flex;
          justify-content: center;
          align-items: center;
        }
    }
  }
}
</style>
